package com.jd.cmdb.tsc.zk.listener;

import com.jd.cmdb.tsc.zk.exception.ZKExceptionHandler;
import com.jd.cmdb.tsc.zk.service.ZKService;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
import org.apache.curator.framework.state.ConnectionState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

/**
 * Created by tianzhengguo on 2016/1/20.
 */
public class LeaderSelListener implements LeaderSelectorListener {
    private static final Logger logger = LoggerFactory.getLogger(LeaderSelListener.class);

    private CountDownLatch leaderLatch = new CountDownLatch(1);

    private CountDownLatch tscNodeLatch;
    private ZKService zkService;

    public LeaderSelListener(CountDownLatch tscNodeLatch,ZKService zkService) {
        this.tscNodeLatch = tscNodeLatch;
        this.zkService = zkService;
    }

    /**
     * @param client the client
     * @throws Exception any errors
     */
    @Override
    public void takeLeadership(CuratorFramework client) throws Exception {
        try {
            tscNodeLatch.countDown();
            logger.info("当前客户端成为leader,leaderId为:{}", zkService.getLeaderSelector().getId());
            leaderLatch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            ZKExceptionHandler.handlerZKException(e);
        }
    }

    /**
     * @param client   the client
     * @param newState the new state
     */
    @Override
    public void stateChanged(CuratorFramework client, ConnectionState newState) {
        logger.info("连接状态发生改变:{}", newState.toString());
        try {
            switch (newState) {
                case RECONNECTED: {

                }
                case LOST: {
                    while (zkService.isExist(zkService.getTSCNode()));
                    zkService.init();
                }
                case SUSPENDED:{

                }
            }
        }catch (Exception e){
            ZKExceptionHandler.handlerZKException(e);

        }
    }
}
